package org.wheel.plugins.toolkit.sql.segment.having;

import lombok.RequiredArgsConstructor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.conditional.OrExpression;
import org.wheel.plugins.toolkit.sql.enums.LogicalOp;

import java.util.ArrayList;
import java.util.List;

/**
 * ========== 3. 容器节点（可再放容器或叶子） ==========
 */
@RequiredArgsConstructor
public final class HavingGroup implements HavingElement {

    private final LogicalOp op;
    private final List<HavingElement> children = new ArrayList<>();

    public HavingGroup add(HavingElement e) {
        children.add(e);
        return this;
    }

    @Override
    public Expression toExpression() {
        return children.stream()
                .map(HavingElement::toExpression)
                .reduce((l, r) -> op == LogicalOp.AND ?
                        new AndExpression(l, r) : new OrExpression(l, r))
                .orElse(null);
    }
}
